package com.ebo.common.smart.parser;

import cn.hutool.core.text.StrSplitter;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.ebo.common.smart.AddressDataLoader;
import com.ebo.common.smart.RegexConstant;
import com.ebo.common.smart.TextHolder;
import com.ebo.common.smart.domain.UserInfo;

import java.util.List;

/**
 * 姓名解析器
 */
public class NameParser {

    private AddressDataLoader addressDataLoader;

    public NameParser(AddressDataLoader addressDataLoader) {
        this.addressDataLoader = addressDataLoader;
    }

    public void parse(UserInfo userInfo, List<String> textList, TextHolder textHolder) {
        String name = matchByFamilyName(textList);

        if (name == null) {
            name = byLen(textList);
        }
        if (name == null) {
            name = matchName(textList);
        }

        if (name != null) {
            userInfo.setName(name);
            textHolder.removeText(name);
        }
    }

    private String matchName(List<String> textList) {
        int minLen = 99;
        String minName = null;
        for (String name : textList) {
            if (StrUtil.isEmpty(name)) {
                continue;
            }
            if (name.length() < minLen) {
                if (addressDataLoader.provinceStartWith(name)) {
                    continue;
                }
                minLen = name.length();
                minName = name;
            }
        }
        return minName;
    }


    /**
     * 根据字符长度来匹配
     */
    private String byLen(List<String> textList) {
        int minLen = 5;
        String minName = null;
        for (String name : textList) {
            if (StrUtil.isEmpty(name)) {
                continue;
            }

            if (name.length() < minLen) {
                minLen = name.length();
                minName = name;
            }
        }
        return minName;
    }

    /**
     * 根据姓来匹配
     *
     * @param textList
     * @return
     */
    private String matchByFamilyName(List<String> textList) {
        for (String text : textList) {
            for (String name : StrSplitter.splitByRegex(text, RegexConstant.SPECIAL, 0, true, true)) {
                if (ReUtil.isMatch(RegexConstant.SURNAME_LIST, name)) {
                    return name;
                }
            }
        }
        return null;
    }


}
